
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class LuckPage extends StatefulWidget {

  @override
  _LuckPageState createState() => _LuckPageState();
}

class _LuckPageState extends State<LuckPage> with TickerProviderStateMixin{
  List<String> rewardsList = [];
  int mIndex = -1;
  late Animation<int> _selectedIndexTween;
  late AnimationController _startAnimateController;

  @override
  void initState() {
    super.initState();
    rewardsList
      ..add("images/gift1.jpg")
      ..add("images/gift2.jpg")
      ..add("images/gift1.jpg")
      ..add("images/gift2.jpg")
      ..add("images/gift1.jpg")
      ..add("images/gift2.jpg")
      ..add("images/gift1.jpg")
      ..add("images/gift2.jpg");

    _startAnimateController = AnimationController(duration: Duration(milliseconds: 2000), vsync: this);
    _selectedIndexTween = _initSelectIndexTween(end: 8);

    // 动画监听
    _startAnimateController.addListener(() {
      // 更新选中的下标
      mIndex = _selectedIndexTween.value ;
      print(mIndex);
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('抽奖'),
        actions: [
          TextButton(onPressed: (){
            _start();
          }, child: Text('开始', style: TextStyle(color: Colors.white),),),
        ],
      ),
      body: Container(
        width: 300,
        height: 300,
        child: GridView.builder(
            itemCount: 8,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4, crossAxisSpacing: 4, mainAxisSpacing: 4),
            itemBuilder: (context, index) {
              return Container(
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    // Image.asset(rewardsList[index]),
                    Container(
                      width: 50,
                      height: 50,
                      color: index == mIndex
                          ? Colors.blue.withOpacity(0.5)
                          : Colors.amber.withOpacity(0.5),
                    ),
                  ],
                ),
              );
            }
            ),
      ),
    );
  }

  _start(){
    // _selectedIndexTween = _initSelectIndexTween(
    //     end: 3 * 8 +
    //         3,
    //     curve: Curves.easeOutCubic);
    _startAnimateController
      ..reset()
      ..duration = Duration(milliseconds: 1000)
      ..forward();
  }

  /// 初始化tween
  ///
  /// [target] 中奖的目标
  Animation<int> _initSelectIndexTween({int begin = 0, int end = 0, Curve curve = Curves.linear}) {
    return StepTween(begin: begin, end: end).animate(CurvedAnimation(parent: _startAnimateController, curve: curve));
  }
}